package com.alm.token.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.AddUpCloseVipData;
import com.alm.token.ui.data.bean.CurrentOrderData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.data.bean.VipOrderListData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.VipApplyView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import baibeiwallet.Constant;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VipApplyActivity extends BaseActivity implements VipApplyView<Object> {
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.tv_viptype)
    TextView tvViptype;
    @BindView(R.id.tv_locknum)
    TextView tvLocknum;
    @BindView(R.id.tv_vipcommit)
    TextView tvVipcommit;
    @BindView(R.id.ly_topapply)
    LinearLayout lyTopapply;
    @BindView(R.id.ly_bodyshow)
    LinearLayout lyBodyshow;
    @BindView(R.id.tv_vipshow)
    TextView tvVipshow;
    @BindView(R.id.tv_locknumshow)
    TextView tvLocknumshow;
    @BindView(R.id.tv_vipstauesshow)
    TextView tvVipstauesshow;
    @BindView(R.id.tv_vipsstarttime)
    TextView tvVipsstarttime;
    @BindView(R.id.tv_vipsyujitime)
    TextView tvVipsyujitime;
    //    @BindView(R.id.rly_upvip)
//    RelativeLayout rlyUpvip;
    @BindView(R.id.tv_vipcancle2)
    TextView tvVipcancle2;
    @BindView(R.id.tv_staueshow1)
    TextView tvStaueshow1;
    @BindView(R.id.tv_viptopshow)
    TextView tvViptopshow;
    @BindView(R.id.img_vipmore)
    ImageView imgVipmore;
    @BindView(R.id.edt_inputg12number)
    EditText edtInputg12number;
    @BindView(R.id.edt_inputg12number2)
    EditText edtInputg12number2;
    @BindView(R.id.tv_g12yiyong)
    TextView tvG12yiyong;
    @BindView(R.id.tv_g12keyong)
    TextView tvG12keyong;
    @BindView(R.id.tv_bizhongshow1)
    TextView tvBizhongshow1;
    @BindView(R.id.tv_bizhongshow2)
    TextView tvBizhongshow2;
    @BindView(R.id.tv_G12bilv)
    TextView tvG12bilv;

    private int inputnumber = 5000;

    private MaterialDialog checkDialog;
    private String vipType = "2";
    private int intentType = 0;
    private AddUpCloseVipData.DataBean dataBean;
    private VipOrderListData.DataBeanX dataBeanX;
    private CurrentOrderData.DataBean.OrderBean orderBean;
    private List<CurrentOrderData.DataBean.VipsBean> vips = new ArrayList<>();
    private CurrentOrderData.DataBean.WalletBean wallet;
    private String acNumber = "0", froNumber = "0";

    private VipOrderListData.DataBeanX.DataBean VipOrderListDataItemdataBean;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_vip_apply;
    }

    @Override
    protected void initVariables() {
        intentType = getIntent().getIntExtra("intentType", 0);//1 量化订单 超级VIP过来
        VipOrderListDataItemdataBean = (VipOrderListData.DataBeanX.DataBean) getIntent().getSerializableExtra("databean");


    }

    @Override
    protected void initViews() {
//        if (intentType == 1) {
//            new ActionBarHelper(this).setTitle("VIP").setRightText("历史");
//        } else
        if (VipOrderListDataItemdataBean != null) {//vip订单历史记录过来
            new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item14));
            rightItem.setVisibility(View.GONE);
            lyTopapply.setVisibility(View.GONE);
            lyBodyshow.setVisibility(View.VISIBLE);
            tvVipcancle2.setVisibility(View.GONE);
            tvVipcommit.setVisibility(View.GONE);
//            rlyUpvip.setVisibility(View.GONE);


            tvVipshow.setText(dataBean.getVipName());

            tvLocknumshow.setText(dataBean.getMoney() + "");

            int status = dataBean.getStatus();
            tvVipstauesshow.setText(status == 1 ? getString(R.string.vip_hint_staue1) : status == 2 ? getString(R.string.vip_hint_staue2) : status == 3 ? getString(R.string.vip_hint_staue3) :
                    status == 4 ? getString(R.string.vip_hint_staue4) : getString(R.string.vip_hint_staue5));// 订单状态 1 : 待生效 2 生效中 3 已升级 4 停止 5 升级中

            tvVipsstarttime.setText(CommonUtil.getDateTimeFromMillisecond(dataBean.getCreateTime()).split(" ")[0]);

            tvVipsyujitime.setText(CommonUtil.getDateTimeFromMillisecond(dataBean.getStartTime()).split(" ")[0]);
            tvStaueshow1.setText(status == 1 ? getString(R.string.vip_hint_predict) : status == 2 ? getString(R.string.vip_hint_takeeffect) : status == 3 ? getString(R.string.vip_hint_predict) :
                    status == 4 ? getString(R.string.vip_hint_close) : getString(R.string.vip_hint_predict));

        } else {
            new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item15)).setRightText(getString(R.string.title_hint_item13));
            lyTopapply.setVisibility(View.VISIBLE);
            lyBodyshow.setVisibility(View.GONE);
            tvVipcancle2.setVisibility(View.GONE);
        }

        tvBizhongshow1.setText(Constant.G12ContractName + getString(R.string.vip_hint_active1));
        tvBizhongshow2.setText(Constant.G12ContractName + getString(R.string.vip_hint_freeze1));


        edtInputg12number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                        edtInputg12number.setText(s);
                        edtInputg12number.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edtInputg12number.setText(s);
                    edtInputg12number.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edtInputg12number.setText(s.subSequence(0, 1));
                        edtInputg12number.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        edtInputg12number2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                        edtInputg12number2.setText(s);
                        edtInputg12number2.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edtInputg12number2.setText(s);
                    edtInputg12number2.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edtInputg12number2.setText(s.subSequence(0, 1));
                        edtInputg12number2.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void loadData() {
        if (VipOrderListDataItemdataBean == null)
            preenter.getCurrentOrderData();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void getData(Object addUpCloseVipData) {
        if (addUpCloseVipData instanceof AddUpCloseVipData) {
            AddUpCloseVipData data = (AddUpCloseVipData) addUpCloseVipData;

            if (data.getStatus() == 0) {
                dataBean = data.getData();
                preenter.getCurrentOrderData();

//                if (dataBean != null) {
//                    lyBodyshow.setVisibility(View.VISIBLE);
//                    tvVipcancle2.setVisibility(View.VISIBLE);
//
//                    boolean maxleave = true;
//
//
//                    for (CurrentOrderData.DataBean.VipsBean vipsBean : vips) {
//                        if (dataBean.getVipLevel() < vipsBean.getId()) {
//                            maxleave = false;
//                            break;
//                        }
//                    }
//
//                    if (maxleave) {
//                        lyTopapply.setVisibility(View.GONE);
//                        new ActionBarHelper(this).setTitle("VIP").setRightText("历史");
////                        rlyUpvip.setVisibility(View.GONE);
//                        tvVipcommit.setVisibility(View.GONE);
//
//
//                    } else {
//                        new ActionBarHelper(this).setTitle("会员升级").setRightText("历史");
//                        tvVipcommit.setText("确认升级");
//                        tvViptopshow.setText("升级VIP等级");
//                        imgVipmore.setVisibility(View.INVISIBLE);
////                        rlyUpvip.setVisibility(View.VISIBLE);
//                        for (CurrentOrderData.DataBean.VipsBean vipsBean : vips) {
//                            if (dataBean.getVipLevel() < vipsBean.getId()) {
//                                vipType = vipsBean.getId()+"";
//                                tvViptype.setText(vipsBean.getName());
//                                break;
//                            }
//                        }
//                    }
//
////                    if (dataBean.getVipName().indexOf("超级") != -1) {
////                        lyTopapply.setVisibility(View.GONE);
////                        new ActionBarHelper(this).setTitle("VIP").setRightText("历史");
//////                        rlyUpvip.setVisibility(View.GONE);
////                        tvVipcommit.setVisibility(View.GONE);
////
////
////                    } else {
////                        new ActionBarHelper(this).setTitle("超级会员升级").setRightText("历史");
////                        tvVipcommit.setText("确认升级");
////                        tvViptopshow.setText("升级VIP等级");
////                        imgVipmore.setVisibility(View.INVISIBLE);
//////                        rlyUpvip.setVisibility(View.VISIBLE);
////                        vipType = "3";
////                        tvViptype.setText("超级会员");
////
////
////                    }
//
//                    tvVipshow.setText(dataBean.getVipName());
//
//                    tvLocknumshow.setText(dataBean.getMoney() + "");
//
//                    int status = dataBean.getStatus();
//                    tvVipstauesshow.setText(status == 1 ? "待生效" : status == 2 ? "生效中" : status == 3 ? "已升级" :
//                            status == 4 ? "停止" : "升级中");// 订单状态 1 : 待生效 2 生效中 3 已升级 4 停止 5 升级中
//
//                    tvVipsstarttime.setText(CommonUtil.getDateTimeFromMillisecond(dataBean.getCreateTime()).split(" ")[0]);
//
//                    tvVipsyujitime.setText(CommonUtil.getDateTimeFromMillisecond(dataBean.getStartTime()).split(" ")[0]);
//                    tvStaueshow1.setText(status == 1 ? "预计" : status == 2 ? "生效" : status == 3 ? "预计" :
//                            status == 4 ? "解绑" : "预计");
//                }
            } else showToast(data.getMsg());
        }
    }

    @Override
    public void getVipOrderListData(Object vipOrderListData) {

    }

    @Override
    public void getCurrentOrderData(Object currentOrderData) {
        if (currentOrderData instanceof CurrentOrderData) {
            CurrentOrderData data = (CurrentOrderData) currentOrderData;

            if (data.getStatus() == 0) {
                vips = data.getData().getVips();
                wallet = data.getData().getWallet();
                orderBean = data.getData().getOrder();
                if (wallet != null) {
                    DecimalFormat dec1 = new DecimalFormat("0.0000");
                    double money = wallet.getFrozenMoney();
                    if (String.valueOf(money).indexOf(".") != -1 && String.valueOf(money).split("\\.")[1].length() >= 4) {
                        tvG12keyong.setText(dec1.format(money));
                    } else
                        tvG12keyong.setText(money + "");
                    money = wallet.getActiveMoney();
                    if (String.valueOf(money).indexOf(".") != -1 && String.valueOf(money).split("\\.")[1].length() >= 4) {
                        tvG12yiyong.setText(dec1.format(money));
                    } else
                        tvG12yiyong.setText(money + "");
                }
                if (orderBean != null) {
                    lyBodyshow.setVisibility(View.VISIBLE);
                    tvVipcancle2.setVisibility(View.VISIBLE);

                    if (vips != null && vips.size() != 0) {
                        new ActionBarHelper(this).setTitle(getString(R.string.vip_hint_title11)).setRightText(getString(R.string.title_hint_item13));
                        tvVipcommit.setText(getString(R.string.vip_hint_warn));
                        tvViptopshow.setText(getString(R.string.vip_hint_warn1));
                        imgVipmore.setVisibility(View.INVISIBLE);
//                        rlyUpvip.setVisibility(View.VISIBLE);

                        vipType = vips.get(vips.size() - 1).getId() + "";
                        tvViptype.setText(vips.get(vips.size() - 1).getName());
                        tvG12bilv.setText(getString(R.string.vip_hint_warn2) + vips.get(vips.size() - 1).getMoney() + "");
                        inputnumber = vips.get(vips.size() - 1).getMoney();
                    } else {
                        lyTopapply.setVisibility(View.GONE);
                        new ActionBarHelper(this).setTitle(getString(R.string.vip_hint_title2)).setRightText(getString(R.string.title_hint_item13));
//                        rlyUpvip.setVisibility(View.GONE);
                        tvVipcommit.setVisibility(View.GONE);
                    }

//                    if (orderBean.getVipName().indexOf("超级") != -1) {
//                        lyTopapply.setVisibility(View.GONE);
//                        new ActionBarHelper(this).setTitle("VIP").setRightText("历史");
////                        rlyUpvip.setVisibility(View.GONE);
//                        tvVipcommit.setVisibility(View.GONE);
//                    } else {
//                        new ActionBarHelper(this).setTitle("超级会员升级").setRightText("历史");
//                        tvVipcommit.setText("确认升级");
//                        tvViptopshow.setText("升级VIP等级");
//                        imgVipmore.setVisibility(View.INVISIBLE);
////                        rlyUpvip.setVisibility(View.VISIBLE);
//                        vipType = "3";
//                        tvViptype.setText("超级会员");
//                    }

                    tvVipshow.setText(orderBean.getVipName());

                    tvLocknumshow.setText(orderBean.getMoney() + "");

                    int status = orderBean.getStatus();
                    tvVipstauesshow.setText(status == 1 ? getString(R.string.vip_hint_staue1) : status == 2 ? getString(R.string.vip_hint_staue2) : status == 3 ? getString(R.string.vip_hint_staue3) :
                            status == 4 ? getString(R.string.vip_hint_staue4) : getString(R.string.vip_hint_staue5));// 订单状态 1 : 待生效 2 生效中 3 已升级 4 停止 5 升级中
                    tvStaueshow1.setText(status == 1 ? getString(R.string.vip_hint_predict) : status == 2 ? getString(R.string.vip_hint_takeeffect) : status == 3 ? getString(R.string.vip_hint_predict) :
                            status == 4 ? getString(R.string.vip_hint_close) : getString(R.string.vip_hint_predict));
                    tvVipsstarttime.setText(CommonUtil.getDateTimeFromMillisecond(orderBean.getCreateTime()));

                    tvVipsyujitime.setText(CommonUtil.getDateTimeFromMillisecond(orderBean.getStartTime()));

                } else {
                    new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item15)).setRightText(getString(R.string.title_hint_item13));
                    tvVipcommit.setText(getString(R.string.vip_hint_warn3));
                    if (vips != null && vips.size() != 0) {
                        vipType = vips.get(vips.size() - 1).getId() + "";
                        tvViptype.setText(vips.get(vips.size() - 1).getName());
                        tvG12bilv.setText(getString(R.string.vip_hint_applynumber, vips.get(vips.size() - 1).getMoney() + ""));
                        inputnumber = vips.get(vips.size() - 1).getMoney();
                    }
                }

            } else showToast(data.getMsg());
        }

    }

    @Override
    public void getStopVipData(Object addUpCloseVipData) {
        if (addUpCloseVipData instanceof AddUpCloseVipData) {
            AddUpCloseVipData data = (AddUpCloseVipData) addUpCloseVipData;
            showToast(data.getMsg());
            finish();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rightItem, R.id.tv_viptype, R.id.tv_locknum, R.id.tv_vipcommit, R.id.tv_vipcancle2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rightItem:
//                showToast("vip历史");
                startActivity(VipOrderListActivity.class);
                break;
            case R.id.tv_viptype:
//                showCheckDiaolg();
                if (tvVipcommit.getText().toString().indexOf(getString(R.string.vip_hint_warn4)) != -1) {//升级超级vip不可选择
                    break;
                }
                showPopupMenu(tvViptype);
                break;
            case R.id.tv_locknum:
//                showToast("locknum");
                break;
            case R.id.tv_vipcommit:

                if (!TextUtils.isEmpty(edtInputg12number2.getText().toString())) {
                    acNumber = edtInputg12number2.getText().toString();
                } else {
                    acNumber = "0";
                }
                if (!TextUtils.isEmpty(edtInputg12number.getText().toString())) {
                    froNumber = edtInputg12number.getText().toString();
                } else {
                    froNumber = "0";
                }
                if (Double.valueOf(acNumber) == 0 && Double.valueOf(froNumber) == 0) {
                    showToast(getString(R.string.vip_hint_warn5));
                    break;
                }
                if (Double.valueOf(acNumber) + Double.valueOf(froNumber) != inputnumber) {
                    showToast(getString(R.string.vip_hint_warn6, inputnumber + ""));
                    break;
                }

                UserWalletData.DataBean.SysMsgBean sysMsgBean1 = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean1.setTitle(tvVipcommit.getText().toString() + getString(R.string.vip_hint_warn7));
                sysMsgBean1.setContent(
                        getString(R.string.vip_hint_warn8, CommonUtil.saveToPoint4WithNo(Double.valueOf(acNumber)), CommonUtil.saveToPoint4WithNo(Double.valueOf(froNumber)), tvVipcommit.getText().toString(), tvViptype.getText()));
                DialogUtils.showInfor1(this, sysMsgBean1, (pwd) -> {

                    DialogUtils.enterPayPsw(this, (pwd1) -> {
                        preenter.getAddUpVipData(vipType, acNumber, froNumber, pwd1);//2 : VIP  3 :超级会员
                    });

                });
//                preenter.getAddUpVipData(tvViptype.getText().toString().indexOf("超级") != -1 ? "3" : "2");//2 : VIP  3 :超级会员
                break;
            case R.id.tv_vipcancle2:
                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean.setTitle(getString(R.string.vip_hint_warn9));
                sysMsgBean.setContent(getString(R.string.vip_hint_warn10));
                DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {

                    DialogUtils.enterPayPsw(this, (pwd1) -> {
                        preenter.getStopVipData(pwd1);//2 : VIP  3 :超级VIP
                    });

                });
//                preenter.getStopVipData();//2 : VIP  3 :超级VIP
                break;
        }
    }

    public void showPopupMenu(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局

        Menu menu = popupMenu.getMenu();
        if (vips != null && vips.size() != 0) {
            for (CurrentOrderData.DataBean.VipsBean vipsBean : vips) {
                menu.add(vipsBean.getName());
            }
        } else {
            menu.add("VIP");
            menu.add("超级会员");
        }


        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);

        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (vips != null && vips.size() != 0) {
                    for (CurrentOrderData.DataBean.VipsBean vipsBean : vips) {
                        if (vipsBean.getName().equalsIgnoreCase(item.getTitle().toString())) {
                            vipType = vipsBean.getId() + "";
                            tvViptype.setText(item.getTitle());
                            tvG12bilv.setText(getString(R.string.vip_hint_applynumber, vipsBean.getMoney() + ""));
                            inputnumber = vipsBean.getMoney();
                            tvLocknum.setText(vipsBean.getMoney() + "");
                            break;
                        }
                    }
                }

//                if (item.getTitle().toString().indexOf("超级") != -1) {
//                    vipType = "3";
//                    tvViptype.setText(item.getTitle());
//                    tvLocknum.setText("10000.0");
//                } else {
//                    vipType = "2";
//                    tvViptype.setText(item.getTitle());
//                    tvLocknum.setText("5000.0");
//                }
                return true;
            }
        });
        popupMenu.show();
    }


    public void hindCheckDiaolg() {
        if (checkDialog == null && checkDialog.isShowing()) {
            checkDialog.dismiss();
        }

    }

}
